package com.mxy.myapplication.activity;

import android.app.Activity;
import android.app.job.JobInfo;
import android.app.job.JobScheduler;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.Toolbar;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;

import com.mxy.myapplication.R;
import com.mxy.myapplication.adapter.AdapterForBanner;
import com.mxy.myapplication.adapter.AdapterForMainActivityViewPager;
import com.mxy.myapplication.asynctask.MyAsyncTask;
import com.mxy.myapplication.fragment.FragmentOfViewPager_Grid;
import com.mxy.myapplication.fragment.FragmentOfViewPager_Linear;
import com.mxy.myapplication.fragment.FragmentOfViewPager_Linear_ItemTouchHelper;
import com.mxy.myapplication.fragment.FragmentOfViewPager_Snap;
import com.mxy.myapplication.fragment.FragmentOfViewPager_Waterfall;
import com.mxy.myapplication.pojo.ParcelableTest;
import com.mxy.myapplication.pojo.Pojo2;
import com.mxy.myapplication.service.GrayService;
import com.mxy.myapplication.service.MyService;
import com.mxy.myapplication.service.MyServiceConnection;
import com.mxy.myapplication.service.MyServiceConnectionOnDifferentProcess;
import com.mxy.myapplication.service.MyServiceOnDifferentProcess;
import com.mxy.myapplication.util.DownloadMissionManageUtil;
import com.mxy.myapplication.util.Util;
import com.mxy.myapplication.util.ViewPagerScroller;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;

/**
 * 后台服务及可视化通知栏操作+材料设计沉浸模式
 * Activity生命周期
 * 创建:onCreate->onStart->onResume
 * 退到后台onPouse->onSaveInstanceState(单参数)->onStop
 * 回到前台onRestart->onStart->onResume
 * 销毁onPouse->onSaveInstanceState(单参数)->onStop->onDestory
 * 横竖屏变更/用户调整系统字体时 onPouse->onSaveInstanceState(单参数)->onStop->onDestory
 * onCreate->onStart->onResume
 * 在manifests中设置configChanges属性后，横竖屏变更   首次变更执行两次onConfigurationChanged
 * 以后切换都是执行一次onConfigurationChanged  变更系统字体，每次变更执行一次onConfigurationChanged
 *
 * @author 马晓勇
 */
public class MainActivity extends BaseActivity implements View.OnClickListener,
        SwipeRefreshLayout.OnRefreshListener, View.OnTouchListener {

    private AppBarLayout appBarLayout;
    private Toolbar toolbar;
    private View tablayouttopview;
    private TabLayout tablayout;
    private ViewPager vp;
    private ViewPager bannervp;
    private LinearLayout indicatorlayout;
    private FloatingActionButton floatingActionButton;
    private ArrayList<Fragment> pagelist = new ArrayList<>();
    private ArrayList<String> namelist = new ArrayList<>();
    private ArrayList<Integer> photolist = new ArrayList<>();

    /**
     * 轮播图是否循环/暂停
     */
    private boolean bannerloop = true;
    /**
     * 是否退出程序
     */
    private boolean notexit = true;
    /**
     * 轮播图ViewPager适配器
     */
    private AdapterForBanner adapterForBanner;
    private int phototype = 1;
    private PopupWindow popupWindow;
    private static MyHandler myHandler;

    public SwipeRefreshLayout swipe;
    private MyServiceConnection myServiceConnection;
    private MyServiceConnectionOnDifferentProcess myServiceConnectionOnDifferentProcess;
    private JobScheduler jobScheduler;

    private DownLoadMissionCompletedReceiver downLoadMissionCompletedReceiver =
            new DownLoadMissionCompletedReceiver();

    private static class MyHandler extends Handler {

        private static WeakReference<MainActivity> mainActivityWeakReference;

        private MyHandler(MainActivity mainActivity) {
            mainActivityWeakReference = new WeakReference<>(mainActivity);
        }

        @Override
        public void handleMessage(Message msg) {
            try {
                MainActivity mainActivity = MyHandler.mainActivityWeakReference.get();
                if (mainActivity != null && !mainActivity.isFinishing()) {
                    mainActivity.handlerMessage(msg);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void handlerMessage(Message msg) {
        switch (msg.what) {
            case 1:
                swipe.setRefreshing(false);
                showBanner();
                bannerloop = true;
                break;
            case 2:
                changeBannerPage();
                break;
            case 3:
                Util.showToast(this, "service通过Message通信");
                break;
            default:
                break;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        myHandler = new MyHandler(this);
        setContentView(R.layout.activity_main);
        initView();
        modeSystemUI();
        setUpTablayout();
        modeBanner();
        showBanner();

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(DownloadMissionManageUtil.BROADCAST_MISSIONCOMPLETED);
        LocalBroadcastManager.getInstance(this).registerReceiver(downLoadMissionCompletedReceiver
                , intentFilter);

        Intent myService = new Intent(this, MyService.class);
        myServiceConnection = new MyServiceConnection(this);
        bindService(myService, myServiceConnection, Activity.BIND_AUTO_CREATE);


        Intent myServiceOnDifferentProcess = new Intent(this, MyServiceOnDifferentProcess.class);
        myServiceConnectionOnDifferentProcess = new MyServiceConnectionOnDifferentProcess();
        bindService(myServiceOnDifferentProcess, myServiceConnectionOnDifferentProcess,
                Activity.BIND_AUTO_CREATE);


        MyAsyncTask as = new MyAsyncTask();
        as.executeOnExecutor(Util.getExecutorService(), 1);

        //文件断点续传下载工具初始化
        DownloadMissionManageUtil.initDownloadMissionManageUtil(getApplicationContext());

        Util.showToast(this, Util.getAppMetaData(getApplication(), "APP_CHANNEL"));


//        ProgressDialog progressDialog=new ProgressDialog(this);
//        progressDialog.setMax(100);
//        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
//        progressDialog.setMessage("进度条");
//        progressDialog.show();
    }

    /**
     * 控件初始化
     */
    private void initView() {
        appBarLayout = (AppBarLayout) findViewById(R.id.AppBarLayout);
        //适配所有屏幕，轮播图占1/3
        ViewGroup.LayoutParams layoutParams = appBarLayout.getLayoutParams();
        layoutParams.height = (getResources().getDisplayMetrics().heightPixels / 3);

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        tablayouttopview = findViewById(R.id.tablayouttopview);
        floatingActionButton = (FloatingActionButton) findViewById(R.id.fab);
        tablayout = (TabLayout) findViewById(R.id.tablayout);
        vp = (ViewPager) findViewById(R.id.ViewPager);
        vp.setOnTouchListener(this);
        bannervp = (ViewPager) findViewById(R.id.bannervp);
        floatingActionButton.setOnClickListener(this);
        //控制ViewPager滑动速度
        ViewPagerScroller viewPagerScroller = new ViewPagerScroller(this);
        viewPagerScroller.setScrollDuration(800);
        viewPagerScroller.initViewPagerScroll(bannervp);

        indicatorlayout = (LinearLayout) findViewById(R.id.indicatorlayout);

        swipe = (SwipeRefreshLayout) findViewById(R.id.swipe);
        swipe.setProgressViewOffset(true, 0, Util.dip2px(this, 40));
        // 为swipe设置下拉刷等待动画颜色
        swipe.setColorSchemeColors(this.getResources().getColor(android.R.color.holo_green_dark),
                this.getResources().getColor(android.R.color.holo_blue_dark),
                this.getResources().getColor(android.R.color.holo_orange_dark));
        swipe.setOnRefreshListener(this);
        //一般字体颜色，选中字体颜色
        tablayout.setTabTextColors(getResources().getColor(android.R.color.white),
                getResources().getColor(R.color.bannertextfocus));
        //选中项下划线颜色
        tablayout.setSelectedTabIndicatorColor(getResources().getColor(R.color.bannertextfocus));
        //滑动模式
        tablayout.setTabMode(TabLayout.MODE_SCROLLABLE);
        //设置tablayout下标线高度
        tablayout.setSelectedTabIndicatorHeight(Util.dip2px(this, 3));
    }

    /**
     * 根据系统版本变更UI效果
     */
    private void modeSystemUI() {
        //系统版本小于5.0
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            tablayouttopview.setVisibility(View.GONE);
            ViewGroup.LayoutParams lp = toolbar.getLayoutParams();
            lp.height = Util.dip2px(this, 35);
            toolbar.setLayoutParams(lp);
        } else {
            tablayouttopview.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 配置tablayout与Viewpager
     */
    private void setUpTablayout() {

        pagelist.add(new FragmentOfViewPager_Linear_ItemTouchHelper());
        pagelist.add(new FragmentOfViewPager_Grid());
        pagelist.add(new FragmentOfViewPager_Linear());
        pagelist.add(new FragmentOfViewPager_Waterfall());
        pagelist.add(new FragmentOfViewPager_Snap());

        namelist.add("线性_可拖动");
        namelist.add("网格_可拖动");
        namelist.add("线性_StickyHeader");
        namelist.add("瀑布");
        namelist.add("带阻尼的RecyclerView");

        vp.setOffscreenPageLimit(namelist.size());
        AdapterForMainActivityViewPager vpadapter =
                new AdapterForMainActivityViewPager(getSupportFragmentManager(), pagelist,
                        namelist);
        vp.setAdapter(vpadapter);

        tablayout.setupWithViewPager(vp, true);
    }

    /**
     * 初始化轮播图
     */
    private void modeBanner() {
        adapterForBanner = new AdapterForBanner(this, photolist, bannervp);
        bannervp.addOnPageChangeListener(new BannerViewPagerPageChangeListener());
        bannervp.setOffscreenPageLimit(3);
        bannervp.setPageMargin(Util.dip2px(this, 8));
        bannervp.setAdapter(adapterForBanner);

        //4秒切换
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (notexit) {
                    try {
                        Thread.sleep(4000);
                        //尽量避免变更图片后立即切换
                        if (bannerloop) {
                            myHandler.sendMessage(myHandler.obtainMessage(2));
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    /**
     * 轮播图自动切换图片
     */
    private void changeBannerPage() {
        if (photolist.size() > 1 && bannerloop) {
            //切换下一页
            bannervp.setCurrentItem(bannervp.getCurrentItem() + 1);
        }
    }

    /**
     * 设置轮播图滑动指示器
     */
    private void initBannerIndicator() {
        indicatorlayout.removeAllViews();
        for (int i = 0; i < photolist.size(); i++) {
            View v = new View(this);
            v.setBackgroundResource(R.drawable.unchecked);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(Util.dip2px(this, 7),
                    Util.dip2px(this, 7));
            lp.setMargins(Util.dip2px(this, 5), 0, Util.dip2px(this, 5), 0);
            v.setLayoutParams(lp);
            indicatorlayout.addView(v);
        }
    }

    /**
     * 变更轮播指示器
     */
    private void indicatorChange() {
        for (int i = 0; i < indicatorlayout.getChildCount(); i++) {
            if (i == AdapterForBanner.getPhotoPosition(bannervp.getCurrentItem(),
                    photolist.size())) {
                View v = indicatorlayout.getChildAt(i);
                v.setBackgroundResource(R.drawable.checked);
            } else {
                View v = indicatorlayout.getChildAt(i);
                v.setBackgroundResource(R.drawable.unchecked);
            }
        }
    }

    /**
     * 展示轮播
     */
    private void showBanner() {
        photolist.clear();
        //先添加图片，
        switch (phototype) {
            case 1:
                photolist.add(R.drawable.jj1);
                photolist.add(R.drawable.jj2);
                photolist.add(R.drawable.jj3);
                break;
            case 2:
                photolist.add(R.drawable.bleach1);
                photolist.add(R.drawable.bleach2);
                photolist.add(R.drawable.bleach3);
                break;
            case 3:
                photolist.add(R.drawable.guanlan1);
                photolist.add(R.drawable.guanlan2);
                photolist.add(R.drawable.guanlan3);
                break;
            default:
                break;
        }


        adapterForBanner.notifyDataSetChanged();

        //然后设置指示器
        initBannerIndicator();
        //只有一张图，不能滑动
        if (photolist.size() < 2) {
            //轮播图默认显示首页
            bannervp.setCurrentItem(0, false);
        } else {//多张图
            //禁止滑动跳转，否则就麻烦了
            bannervp.setCurrentItem(AdapterForBanner.MAX_BANNER_SIZE / 2, false);
        }
        //默认首张图片被选中
        View v = indicatorlayout.getChildAt(0);
        v.setBackgroundResource(R.drawable.checked);
    }


    @Override
    public void onClick(View v) {
        if (v == floatingActionButton) {
            //相同进程,通过Binder调用service中方法
//      if(myServiceConnection.getBinder()!=null){
//        myServiceConnection.getBinder().callmethodOfService2();
//      }


            //跳转扫描二维码界面
            //Intent默认会携带"android.intent.category.DEFAULT",
            // 所以隐式启动的组件在manifest文件的intent-filter中必须包含 <category android:name="android.intent
            // .category.DEFAULT" />
            //startActivity方法必须使用trycatch，因为会抛出No Activity found to handle Intent异常
            Intent intent = new Intent("com.mxy.myapplication.activity.ScanActivity.class");
            //manifast文件中的Category需要>=代码中的Category
            intent.addCategory("abc");

            ArrayList<Pojo2> pojo2s = new ArrayList<>(2);
            Pojo2 p1 = new Pojo2(173);
            Pojo2 p2 = new Pojo2(174);
            pojo2s.add(p1);
            pojo2s.add(p2);

            ParcelableTest parcelableTest = new ParcelableTest("马晓勇", 32, pojo2s);

            intent.putExtra("Parcelable", parcelableTest);
            try {
                startActivity(intent);
            } catch (Exception e) {
                Util.showToast(this, "组件未装载");
                e.printStackTrace();
            }

            try {
                //测试AIDL跨进程通信,通过Binder调用service中方法
                if (myServiceConnectionOnDifferentProcess.getiMyAidlInterface() != null) {
                    System.out.println("跨进程通信输出年龄 : " + myServiceConnectionOnDifferentProcess.getiMyAidlInterface().getAge());
                }
            } catch (RemoteException e) {
                e.printStackTrace();
            }
//      startActivity(new Intent(this, TestTouchActivity.class));
        }
    }

    /**
     * 创建一个JobSchedule
     */
    private void createAJobSchedule() {
        //5.0以上才能使用JobService
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            jobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
            if (jobScheduler != null) {
                //第一个参数为任务的id,在需要取消该任务时使用  : jobScheduler.cancel(1);
                JobInfo jobInfo = new JobInfo.Builder(1, new ComponentName(getPackageName(),
                        GrayService.class.getName()))
                        .setPeriodic(5 * 1000)
                        //设置需要的网络条件，默认NETWORK_TYPE_NONE
                        .setRequiredNetworkType(JobInfo.NETWORK_TYPE_NONE)
                        // 设置任务运行最少延迟时间  该方法不能与setPeriodic()同时调用
//                  .setMinimumLatency(1000)
                        // 设置deadline，若到期还没有达到规定的条件则会开始执行  该方法不能与setPeriodic()同时调用
//                  .setOverrideDeadline(5000)
                        // 设置是否充电的条件,默认false
                        .setRequiresCharging(true)
                        // 设置手机是否空闲的条件,默认false
                        .setRequiresDeviceIdle(false)
//如果设置该句，那么需要在manifest文件中申请    <uses-permission android:name="android.permission
// .RECEIVE_BOOT_COMPLETED"/>权限
//          .setPersisted(true)//设备重启之后你的任务是否还要继续执行
                        .build();
                jobScheduler.schedule(jobInfo);
            }
        }
    }

    @Override
    public void onRefresh() {
        switch (phototype) {
            case 1:
                phototype = 2;
                break;
            case 2:
                phototype = 3;
                break;
            case 3:
                phototype = 1;
                break;
            default:
                break;
        }
        bannerloop = false;
        myHandler.sendMessageDelayed(myHandler.obtainMessage(1), 3000);
    }

    public static Message getMessage(int what) {
        return myHandler.obtainMessage(what);
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {

        if (v == vp) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_MOVE:
                    swipe.setEnabled(false);
                    break;
                case MotionEvent.ACTION_CANCEL:
                case MotionEvent.ACTION_UP:
                    swipe.setEnabled(true);
                    break;
                default:
                    break;
            }
        }
        return false;
    }

    @Override
    protected void onResume() {
        super.onResume();
        bannerloop = true;
    }

    @Override
    protected void onStop() {
        super.onStop();
        bannerloop = false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        DownloadMissionManageUtil.destroyDownloadMissionManageUtil();
        bannerloop = false;
        notexit = false;
        try {
            unbindService(myServiceConnection);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            unbindService(myServiceConnectionOnDifferentProcess);
        } catch (Exception e) {
            e.printStackTrace();
        }
        LocalBroadcastManager.getInstance(this).unregisterReceiver(this.downLoadMissionCompletedReceiver);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
    }

    @Override
    public void onBackPressed() {

        if (popupWindow != null && popupWindow.isShowing()) {
            popupWindow.dismiss();
            Util.changeWindowAlpha(MainActivity.this, 1f);
        } else {
            moveTaskToBack(true);
        }
    }

    /**
     * --------------------------------------------------popwindow显示
     * 展示popupwindow
     * 注：控件的LayoutParams在没有在屏幕上绘制完毕之前，都是0，所以有些地方的数值是手动先计算好的
     */
    public void setPopupWindow(ImageView itemClickImageView) {//传入点击item图片对象

        Util.changeWindowAlpha(this, 0.5f);
        View v = getLayoutInflater().inflate(R.layout.popupview, null, false);
        View popdownlayout = v.findViewById(R.id.popdownlayout);
        popdownlayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Util.showToast(MainActivity.this, "我是底部弹起的imageview");
            }
        });


        popupWindow = new PopupWindow(v, LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT);
        Util.setPopwindowAnim(this, itemClickImageView, popupWindow, v, 1.25f, Util.dip2px(this,
                200), Util.dip2px(this, 25));
    }

    /**
     * 轮播图滑动监听
     */
    private class BannerViewPagerPageChangeListener implements ViewPager.OnPageChangeListener {


        /**
         * 通过日志 得出来  ViewPager滑动的时候  回调的方法顺序为
         onPageScrollStateChanged()// state == ViewPager.SCROLL_STATE_DRAGGING  正在滑动状态

         onPageScrolled()  //滑动状态

         onPageScrollStateChanged() // state ==SCROLL_STATE_SETTLING  自动沉降状态

         onPageSelected() // 选中状态

         onPageScrolled()  //滑动状态

         onPageScrollStateChanged()  //state==SCROLL_STATE_IDLE   空闲状态  滑动结束
         *
         * **/


        /**
         * 这个方法在手指操作屏幕的时候发生变化。有三个值：0（END）,1(PRESS) , 2(UP) 。
         * 当用手指滑动翻页时，手指按下去的时候会触发这个方法，state值为1，手指抬起时，如果发生了滑动（即使很小），这个值会变为2，然后最后变为0
         * 。总共执行这个方法三次。一种特殊情况是手指按下去以后一点滑动也没有发生，这个时候只会调用这个方法两次，state值分别是1,0 。
         * 当setCurrentItem翻页时，会执行这个方法两次，state值分别为2,0。
         **/
        @Override
        public void onPageScrollStateChanged(int state) {

            switch (state) {
                case ViewPager.SCROLL_STATE_DRAGGING:
                case ViewPager.SCROLL_STATE_SETTLING:
                    bannerloop = false;
                    break;
                case ViewPager.SCROLL_STATE_IDLE:
                    bannerloop = true;
                    break;
                default:
                    break;
            }
        }

        /**
         * 有三个参数，第一个position，这个参数要特别注意一下。当用手指滑动时，如果手指按在页面上不动，position和当前页面index是一致的；
         * 如果手指向左拖动（相应页面向右翻动），这时候position大部分时间和当前页面是一致的，只有翻页成功的情况下最后一次调用才会变为目标页面；
         * 如果手指向右拖动（相应页面向左翻动），这时候position大部分时间和目标页面是一致的，只有翻页不成功的情况下最后一次调用才会变为原页面。
         * 当直接设置setCurrentItem翻页时，如果是相邻的情况（比如现在是第二个页面，跳到第一或者第三个页面），如果页面向右翻动，
         * 大部分时间是和当前页面是一致的，只有最后才变成目标页面；如果向左翻动，position和目标页面是一致的。这和用手指拖动页面翻动是基本一致的。
         * 如果不是相邻的情况，比如我从第一个页面跳到第三个页面，position先是0，然后逐步变成1，然后逐步变成2；我从第三个页面跳到第一个页面，
         * position先是1，然后逐步变成0，并没有出现为2的情况。
         * positionOffset是当前页面滑动比例，如果页面向右翻动，这个值不断变大，最后在趋近1的情况后突变为0。如果页面向左翻动，这个值不断变小，
         * 最后变为0。 positionOffsetPixels是当前页面滑动像素，变化情况和positionOffset一致。
         **/
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        /**
         * 这个方法有一个参数position，代表哪个页面被选中。
         * 当用手指滑动翻页的时候，如果翻动成功了（滑动的距离够长），手指抬起来就会立即执行这个方法， position就是当前滑动到的页面。
         * 如果直接setCurrentItem翻页，那position就和setCurrentItem的参数一致，
         * 这种情况在onPageScrolled执行方法前就会立即执行。
         **/
        @Override
        public void onPageSelected(int position) {
            indicatorChange();
        }
    }

    private class DownLoadMissionCompletedReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (DownloadMissionManageUtil.BROADCAST_MISSIONCOMPLETED.equals(intent.getAction())) {
                String fileAddress =
                        intent.getStringExtra(DownloadMissionManageUtil.FILE_ADDRESS_INTENT_KEY);
                File file = new File(fileAddress);
                if (file.exists()) {
                    Util.openAPK(MainActivity.this, file);
                }
            }
        }
    }
}